//
//  UIViewController+Extension.m
//  FamilyDoctorUser
//
//  Created by kinglian_iOS_000 on 2017/8/12.
//  Copyright © 2017年 kinglian. All rights reserved.
//

#import "UIViewController+Extension.h"

@implementation UIViewController (Extension)

+ (void)app_removeCurrenStackVCWithCoordinateVC:(UIViewController *)coordinateVC
                                   removeIndex:(NSUInteger)removeIndex
                                  removeLength:(NSUInteger)removeLength
{
    if (!coordinateVC.navigationController) {
        return;
    }
    
    NSMutableArray *vcArray = coordinateVC.navigationController.childViewControllers.mutableCopy;
    
    NSInteger coordinateVCIndex = [vcArray indexOfObject:coordinateVC];
    if (coordinateVCIndex == NSNotFound) {
        return;
    }
    
    if (coordinateVCIndex < removeIndex + removeLength) { // 导航控制器栈里面至少留一个控制器
        return;
    }
    
    NSRange range = NSMakeRange(coordinateVCIndex - removeIndex - removeLength + 1, removeLength);
    NSLog(@"哈哈哈哈： %ld-%ld", range.location, range.length);
    
    [vcArray removeObjectsInRange:range];
    
    [coordinateVC.navigationController setViewControllers:vcArray];
}

+ (UIViewController *)app_getCurrentVC {
    UIViewController *rootViewController = [UIApplication sharedApplication].keyWindow.rootViewController;
    
    UIViewController *currentVC = [self getCurrentVCFrom:rootViewController];
    
    return currentVC;
}

+ (UIViewController *)getCurrentVCFrom:(UIViewController *)rootVC {
    UIViewController *currentVC;
    
    if ([rootVC presentedViewController]) { // 视图是被presented出来的
        rootVC = [rootVC presentedViewController];
    }
    
    if ([rootVC isKindOfClass:[UITabBarController class]]) { // 根视图为UITabBarController
        currentVC = [self getCurrentVCFrom:[(UITabBarController *)rootVC selectedViewController]];
        
    }else if ([rootVC isKindOfClass:[UINavigationController class]]) { // 根视图为UINavigationController
        currentVC = [self getCurrentVCFrom:[(UINavigationController *)rootVC visibleViewController]];
        
    }else {  // 根视图为非导航类
        currentVC = rootVC;
    }
    
    return currentVC;
}


@end
